//
//  WWPictureView.swift
//  SinWEiBo
//
//  Created by 胡良志 on 2018/3/30.
//  Copyright © 2018年 HuLiangZhi. All rights reserved.
//

import UIKit
let pictureCell = "pictureCell"

class WWPictureView: UICollectionView {

    var pictureInfos : [WWPictureInfo]?{
        didSet{
            self.reloadData()
        }
    }
    
    
    override func awakeFromNib() {
        self.register(WWPictureViewCell.self, forCellWithReuseIdentifier: pictureCell)
        let nib = UINib(nibName: "WWPictureViewCell", bundle: nil)
        self.register(nib , forCellWithReuseIdentifier: pictureCell)
        self.backgroundColor = UIColor.white
        dataSource = self
        delegate = self
    }
}

extension WWPictureView:UICollectionViewDataSource,UICollectionViewDelegate{
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureInfos?.count ?? 0
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: pictureCell, for: indexPath) as! WWPictureViewCell

        let pictureinfo = self.pictureInfos![indexPath.item]
        cell.pictureInfo = pictureinfo

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        /*
         //配置数据源（图片浏览器每一张图片对应一个 YBImageBrowserModel 实例）
         NSMutableArray *tempArr = [NSMutableArray array];
         
         [self.dataArray0 enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
         YBImageBrowserModel *model = [YBImageBrowserModel new];
         [model setImageWithFileName:obj fileType:@"jpeg"];
         model.sourceImageView = [self getImageViewOfCellByIndexPath:[NSIndexPath indexPathForRow:idx inSection:0]];
         [tempArr addObject:model];
         }];
         
         //创建图片浏览器（注意：更多功能请看 YBImageBrowser.h 文件或者 github readme）
         YBImageBrowser *browser = [YBImageBrowser new];
         browser.dataArray = tempArr;
         browser.currentIndex = indexPath.row;
         
         //展示
         [browser show];
         */
        var tempArray = [Any]()
        //遍历数组
        for (n,c) in (pictureInfos?.enumerated())! {
            print("\(n): '\(c)'")
            
            let model = YBImageBrowserModel()
            model.setUrlWithDownloadInAdvance(c.imageURL!)
            
            let cell = self.cellForItem(at: indexPath) as! WWPictureViewCell
            model.sourceImageView = cell.imageView
            tempArray.append(model)
        }
        //创建图片浏览器
        let browser = YBImageBrowser()
        browser.dataArray = tempArray as! [YBImageBrowserModel]
        browser.currentIndex = UInt(indexPath.item)
        browser.show()
    }
    
}















